package com.zxp.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxp.mall.common.constant.ProductConstant;
import com.zxp.mall.common.utils.PageUtils;
import com.zxp.mall.common.utils.Query;
import com.zxp.mall.product.dao.AttrDao;
import com.zxp.mall.product.entity.AttrAttrgroupRelationEntity;
import com.zxp.mall.product.entity.AttrEntity;
import com.zxp.mall.product.entity.AttrGroupEntity;
import com.zxp.mall.product.entity.CategoryEntity;
import com.zxp.mall.product.service.AttrAttrgroupRelationService;
import com.zxp.mall.product.service.AttrGroupService;
import com.zxp.mall.product.service.AttrService;
import com.zxp.mall.product.service.CategoryService;
import com.zxp.mall.product.vo.AttrRespVo;
import com.zxp.mall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService relationService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo) {
//        报错基本数据
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, entity);
        this.save(entity);
//        保存关联关系
        if (attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrVo.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationEntity.setAttrId(entity.getAttrId());
            relationService.save(relationEntity);
        }
    }

    @Override
    public PageUtils baseList(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ?
                ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        String key = (String) params.get("key");
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(obj -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> attrRespVos = records.stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
//  设置分类 和 分组的名字
//            销售属性不存在分组名字
            if ("base".equalsIgnoreCase(attrType)) {

                AttrAttrgroupRelationEntity relationEntity =
                        relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",
                                attrEntity.getAttrId()));
                if (relationEntity != null) {
                    AttrGroupEntity group = attrGroupService.getById(relationEntity.getAttrGroupId());
                    if (group != null) {
                        attrRespVo.setGroupName(group.getAttrGroupName());
                    }
                }
            }
            CategoryEntity category = categoryService.getById(attrRespVo.getCatelogId());
            if (category != null) {
                attrRespVo.setCatelogName(category.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrRespVos);

        return pageUtils;
    }

    @Cacheable(value = "attr", key = "#root.method.name +':' + #root.args[0] ")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attr = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attr, attrRespVo);

//        分组id
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrgroupRelation = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (attrgroupRelation != null) {
                attrRespVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
//        分组名字

                AttrGroupEntity attrGroup = attrGroupService.getById(attrgroupRelation.getAttrGroupId());
                if (attrGroup != null) {
                    attrRespVo.setGroupName(attrGroup.getAttrGroupName());
                }

            }
        }
//        路径
        Long[] catelogPath = categoryService.findCatelogPath(attr.getCatelogId());
        attrRespVo.setCatelogPath(catelogPath);
//        设置分类名字
        CategoryEntity category = categoryService.getById(attr.getCatelogId());
        if (category != null) {
            attrRespVo.setCatelogName(category.getName());
        }
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        System.out.println("getSearchType--------->" + attrEntity.getSearchType());
//        修改分组关联 基本属性才需要
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            int count = relationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
//            更新
                relationService.update(relationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attr.getAttrId()));
            } else {
//            新增
                relationService.save(relationEntity);
            }
        }
    }

    //    根据分组id 查找关联的所有规格参数
    @Override
    public List<AttrEntity> getRelationAttrs(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = entities.stream().map(elationEntity -> elationEntity.getAttrId()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(attrIds)) {
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    //    获取当前分组 没有被关联的属性
    @Override
    public PageUtils getNoRelationAttrs(Map<String, Object> params, Long attrgroupId) {
//        当前分组只能关联自己所属分类里面的所有属性
        AttrGroupEntity group = attrGroupService.getById(attrgroupId);
        Long catelogId = group.getCatelogId();
//        关联的是别的分组没有引用的属性
//        1. 当前分类下的其他分组
        List<AttrGroupEntity> groupList = attrGroupService.list(
                new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIds = groupList.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());
//        2. 分组关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> attrIds = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
//        3. 从当前分组中移除属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",
                ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (!CollectionUtils.isEmpty(attrIds)) {
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(obj -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> iPage = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        return new PageUtils(iPage);
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        List<Long> ids = baseMapper.selectSearchAttrs(attrIds);
        return ids;
    }
}